#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "globalarray.h"
#include "globalstyle.h"

#include <QMessageBox>
#include <QList>
#include <QString>
#include <QPushButton>
#include <QDebug>
#include <QMouseEvent>
#include <QKeyEvent>
#include <QComboBox>
#include <QTimer>
#include <QTextStream>
#include <QTextCodec>
#include <QVector>
#include <QShortcut>
#include <QHotkey>
#include <QBitmap>
#include <QFont>
#include <QButtonGroup>

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    setWindowTitle(TITLE);
    windowBeautify();
    //用来处理鼠标点击坐标的定时器
    posTimer = new QTimer(this);
    //用来进行ocr并更新文字数组的定时器
    ocrTimer = new QTimer(this);

    //tolerance = 0.99; // 容忍值,粗略忽略鼠标的位置不同导致的影响
    //测试容忍值的临界值
    tolerance = 0.97;
    cutimage = new CutImage();
    mediaPlayer = new QMediaPlayer;
    //安装事件过滤器
    installEventFilter(this);
    installFilter();

    //Python C API
    setenv("PYTHONHOME", "/home/mhc/anaconda3/envs/modelscope", 1);
    setenv("LD_LIBRARY_PATH", "/home/mhc/anaconda3/envs/modelscope/lib", 1);
    Py_Initialize();

    PyRun_SimpleString("import sys");
    PyRun_SimpleString("sys.argv = ['python.py']");
    PyRun_SimpleString("sys.path.append('./')");
    //导入模块
    importPythonModules();
    //导入方法
    importPythonFunctions();
    //导入模型
    PyObject_CallFunction(pDeteImport,NULL);
    PyObject_CallFunction(pRecoImport,NULL);
    //默认设置女声晓晓，语速0，语调0
    onvoicechange(0);
    updateratevalue(0);
    updatepitchvalue(0);

    // 创建全局快捷键实例
    magnifierKey = new QHotkey(QKeySequence("Ctrl+M"), true, this);
    normalizeKey = new QHotkey(QKeySequence("Ctrl+Shift+M"), true, this);
    startKey = new QHotkey(QKeySequence("Ctrl+Alt+C"), true, this);
    quitKey = new QHotkey(QKeySequence("Ctrl+T"), true, this);
    showtextfierKey = new QHotkey(QKeySequence("Ctrl+K"), true, this);
    //预处理
    preHandleTimer = new QTimer(this);
    //preHandleTimer->start(6000);

    // 将子页面添加到QStackedWidget中
    ui->pages->addWidget(ui->page_home);
    ui->pages->addWidget(ui->page_voice);
    ui->pages->addWidget(ui->page_shortcut);
    ui->pages->addWidget(ui->page_settings);
    ui->pages->addWidget(ui->page_generate);
    ui->pages->addWidget(ui->page_tools);
    speakText("欢迎使用麒麟颂语软件");
    initializeWindow();
    setPyttsx3ComboBox();
    // 默认不开启语音提示功能
    on_setPlayInvisible_clicked();
    // 默认显示第一个子页面
    ui->pages->setCurrentIndex(0);
}
//初始化设置
void MainWindow::initializeWindow()
{
    //initialize
    isTextWindowEnabled = false;
    zoom = 4.0;
    //加载界面
    fontSize = 1;
    ui->radioButton_microsoft->setChecked(true);
    ttsMode = 2;
    QString styleSheet = GlobalStyle::getInstance().getStyle(0, fontSize);
    MainWindow::setStyleSheet(styleSheet);
    menuIcon();
    showTextBox();
    playAudio();
    connectSlots();
    ui->slider_rate->setValue(30);
    ui->slider_pitch->setValue(30);

    // 获取当前应用程序的工作目录,作为默认的音频生成地址
    QString currentDir = QDir::currentPath();
    QString defaultName = "/test.mp3";
    ui->audioPath->setText(currentDir+defaultName);
    QString text;
    switch (ttsMode) {
    case 1:
        text = ui->comboBox_pyttsx3->currentText();
        ui->label_voice->setText(text);
        break;
    case 2:
        text = ui->comboBox_microsoft->currentText();
        ui->label_voice->setText(text);
        break;
    case 3:
        text = ui->comboBox_google->currentText();
        ui->label_voice->setText(text);
        break;
    default:
        break;
    }
}
//根据当前环境下已有的引擎中的声音列表来设置comboBox
void MainWindow::setPyttsx3ComboBox()
{
    PyObject* pResult = PyObject_CallObject(setPyttsx3,NULL);
    if(pResult) {
        //将返回值转化为string类型
        PyObject* repr = PyObject_Repr(pResult);
        PyObject* str = PyUnicode_AsEncodedString(repr, "utf-8", "strict");
        QString result = PyBytes_AsString(str);
        QList<QString> stringList = result.mid(1, result.length() - 2).split("-");
        foreach (const QString &str, stringList) {
            ui->comboBox_pyttsx3->addItem(str);
        }
        Py_XDECREF(pResult);  // 释放Python对象
    } else {
        PyErr_Print();
    }
}
//手动实现界面随着鼠标的拖动而移动
void MainWindow::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        lastMousePosition = event->globalPos() - frameGeometry().topLeft();
        event->accept();
    }
}
void MainWindow::mouseMoveEvent(QMouseEvent *event)
{
    if (event->buttons() & Qt::LeftButton)
    {
        move(event->globalPos() - lastMousePosition);
        event->accept();
    }
}

//pythonAPI function: 将连接槽函数的操作集成在一起
void MainWindow::connectSlots()
{
    // 界面变化和鼠标位置
    connect(posTimer, &QTimer::timeout, this, &MainWindow::mouseInText);
    connect(ocrTimer, &QTimer::timeout, this, &MainWindow::handleImgChange);
    // 连接快捷键触发的槽函数
    connect(magnifierKey, &QHotkey::activated, this, &MainWindow::magnifierWindowSlot);
    connect(normalizeKey, &QHotkey::activated, this, &MainWindow::normalizeWindow);
    connect(startKey, &QHotkey::activated, this, &MainWindow::hotkeyStart);
    connect(quitKey, &QHotkey::activated, this, &MainWindow::hotkeyQuit);
    connect(showtextfierKey, &QHotkey::activated, this, &MainWindow::showTextWindowSlots);
    // 连接 QSlider 的 valueChanged 信号到槽函数来更新 QLabel 的值
    connect(ui->slider_rate, SIGNAL(valueChanged(int)), this, SLOT(updateratevalue(int)));
    connect(ui->slider_pitch, SIGNAL(valueChanged(int)), this, SLOT(updatepitchvalue(int)));
    connect(ui->magnifierSlider, SIGNAL(valueChanged(int)), this, SLOT(updatezoomvalue(int)));
    connect(ui->menuList, SIGNAL(currentItemChanged(QListWidgetItem*, QListWidgetItem*)), this, SLOT(menulistItemChanged(QListWidgetItem*, QListWidgetItem*)));
    // 将QListWidget的currentRowChanged信号连接到槽函数on_menuList_currentRowChanged
    connect(ui->menuList, SIGNAL(currentRowChanged(int)), this, SLOT(on_menuList_currentRowChanged(int)));
    //tts
    connect(ui->slider_pitch, &QSlider::valueChanged, this, &MainWindow::setPitch);
    connect(ui->slider_rate, &QSlider::valueChanged, this, &MainWindow::setRate);
    //todo  connect(ui->comboBox_voice, QOverload<int>::of(&QComboBox::currentIndexChanged), this, &MainWindow::onvoicechange);
    connect(preHandleTimer, &QTimer::timeout, this, &MainWindow::preHandle);
    //界面切换的槽函数
    connect(ui->comboBoxStyle, SIGNAL(currentIndexChanged(int)), this, SLOT(onComboBoxIndexChanged(int)));
    //tts-version
    connect(ui->radioButton_pytts,SIGNAL(toggled(bool)),this,SLOT(checkSlot1(bool)));
    connect(ui->radioButton_microsoft,SIGNAL(toggled(bool)),this,SLOT(checkSlot2(bool)));
    connect(ui->radioButton_google,SIGNAL(toggled(bool)),this,SLOT(checkSlot3(bool)));
}

//pythonAPI function: 保存音频文件
void MainWindow::generateAudio(QString text, QString path)
{
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* arg2 = PyUnicode_DecodeUTF8(path.toUtf8().constData(), strlen(path.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(2, arg1, arg2);

    PyObject_CallObject(generateMp3, args);
    Py_DECREF(args);
}

//style function: 美化界面
void MainWindow::windowBeautify()
{
    //设置透明度
    //setWindowOpacity(0.95);
    //取消标题栏
    setWindowFlags(Qt::FramelessWindowHint);
    this->setWindowFlags(Qt::FramelessWindowHint | Qt::WindowSystemMenuHint | Qt::WindowMinMaxButtonsHint);
    //设置圆角
    QBitmap bmp(this->size());
    bmp.fill();
    QPainter p(&bmp);
    p.setPen(Qt::NoPen);
    p.setBrush(Qt::black);
    p.drawRoundedRect(bmp.rect(),20,20);//像素为10的圆角
    setMask(bmp);
    // 为窗口添加鼠标事件处理,因为取消了标题栏，所以自己重写界面移动逻辑
    setMouseTracking(true);
}

//style function: 给菜单栏的每项添加图标
void MainWindow::menuIcon()
{
    QListWidgetItem *item1 = ui->menuList->item(0); // 通过行号获取项
    if (item1) {
        QIcon icon1(":/icons/images/home.png");
        item1->setIcon(icon1);
    }
    QListWidgetItem *item2 = ui->menuList->item(1); // 通过行号获取项
    if (item2) {
        QIcon icon2(":/icons/images/person.png");
        item2->setIcon(icon2);
    }
    QListWidgetItem *item3 = ui->menuList->item(2); // 通过行号获取项
    if (item3) {
        QIcon icon3(":/icons/images/shortcut.png");
        item3->setIcon(icon3);
    }
    QListWidgetItem *item4 = ui->menuList->item(3); // 通过行号获取项
    if (item4) {
        QIcon icon4(":/icons/images/settings.png");
        item4->setIcon(icon4);
    }
    QListWidgetItem *item5 = ui->menuList->item(4); // 通过行号获取项
    if (item5) {
        QIcon icon5(":/icons/images/generate.png");
        item5->setIcon(icon5);
    }
    QListWidgetItem *item6 = ui->menuList->item(5); // 通过行号获取项
    if (item6) {
        QIcon icon6(":/icons/images/tools.png");
        item6->setIcon(icon6);
    }
}

//style function:小喇叭
void MainWindow::playAudio()
{
    //小喇叭图标用来提供语音提示
    QLabel *languageAudio = ui->play_language;
    QLabel *voiceAudio = ui->play_voice;
    QLabel *ThemeAudio = ui->play_changeTheme;
    QLabel *startAudio = ui->play_start;
    QLabel *quitAudio = ui->play_quit;
    QLabel *item1Audio = ui->play_menuItem1;
    QLabel *item2Audio = ui->play_menuItem2;
    QLabel *item3Audio = ui->play_menuItem3;
    QLabel *item4Audio = ui->play_menuItem4;
    QLabel *item5Audio = ui->play_menuItem5;
    QLabel *item6Audio = ui->play_menuItem6;
    QLabel *shortcutAudio1 = ui->play_shortcut1;
    QLabel *shortcutAudio2 = ui->play_shortcut2;
    QLabel *voiceDesAudio = ui->play_voicedescription;
    QLabel *microAudio = ui->play_microsoft;
    QLabel *googleAudio = ui->play_google;
    QLabel *audio1 = ui->Audio1;
    QLabel *audio2 = ui->Audio2;
    QLabel *audio3 = ui->Audio3;
    QLabel *audio4 = ui->Audio4;
    QLabel *audio5 = ui->Audio5;
    QLabel *audio6 = ui->Audio6;
    QLabel *audio7 = ui->Audio7;
    QLabel *audio8 = ui->Audio8;
    QLabel *audio9 = ui->Audio9;
    QLabel *audio11 = ui->Audio11;
    QLabel *audio12 = ui->Audio12;
    QLabel *audio13 = ui->Audio13;

    QPixmap originalPixmapPlay(":/icons/images/play.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthp = 40; // 设置新的宽度
    int heightp = 40; // 设置新的高度
    QPixmap scaledPixmap2 = originalPixmapPlay.scaled(widthp, heightp, Qt::KeepAspectRatio);
    QPalette palette2;
    palette2.setBrush(QPalette::Background, scaledPixmap2);
    languageAudio->setAutoFillBackground(true);
    voiceAudio->setAutoFillBackground(true);
    ThemeAudio->setAutoFillBackground(true);
    startAudio->setAutoFillBackground(true);
    quitAudio->setAutoFillBackground(true);
    item1Audio->setAutoFillBackground(true);
    item2Audio->setAutoFillBackground(true);
    item3Audio->setAutoFillBackground(true);
    item4Audio->setAutoFillBackground(true);
    item5Audio->setAutoFillBackground(true);
    item6Audio->setAutoFillBackground(true);
    audio1->setAutoFillBackground(true);
    audio2->setAutoFillBackground(true);
    audio3->setAutoFillBackground(true);
    audio4->setAutoFillBackground(true);
    audio5->setAutoFillBackground(true);
    audio6->setAutoFillBackground(true);
    audio7->setAutoFillBackground(true);
    audio8->setAutoFillBackground(true);
    audio9->setAutoFillBackground(true);
    audio11->setAutoFillBackground(true);
    audio12->setAutoFillBackground(true);
    audio13->setAutoFillBackground(true);
    shortcutAudio1->setAutoFillBackground(true);
    shortcutAudio2->setAutoFillBackground(true);
    voiceDesAudio->setAutoFillBackground(true);
    microAudio->setAutoFillBackground(true);
    googleAudio->setAutoFillBackground(true);
    languageAudio->setPalette(palette2);
    voiceAudio->setPalette(palette2);
    ThemeAudio->setPalette(palette2);
    startAudio->setPalette(palette2);
    quitAudio->setPalette(palette2);
    item1Audio->setPalette(palette2);
    item2Audio->setPalette(palette2);
    item3Audio->setPalette(palette2);
    item4Audio->setPalette(palette2);
    item5Audio->setPalette(palette2);
    item6Audio->setPalette(palette2);
    shortcutAudio1->setPalette(palette2);
    shortcutAudio2->setPalette(palette2);
    voiceDesAudio->setPalette(palette2);
    microAudio->setPalette(palette2);
    googleAudio->setPalette(palette2);
    audio1->setPalette(palette2);
    audio2->setPalette(palette2);
    audio3->setPalette(palette2);
    audio4->setPalette(palette2);
    audio5->setPalette(palette2);
    audio6->setPalette(palette2);
    audio7->setPalette(palette2);
    audio8->setPalette(palette2);
    audio9->setPalette(palette2);
    audio11->setPalette(palette2);
    audio12->setPalette(palette2);
    audio13->setPalette(palette2);
}

//style function:为其他的标签添加图标
void MainWindow::showTextBox()
{
    //添加软件图标
    QLabel *logo = ui->appLogo;
    QPixmap appPixmap(":/icons/images/app.png"); // 替换为你的图片路径
    // 调整图片尺寸
    int widthApp = 80; // 设置新的宽度
    int heightApp = 80; // 设置新的高度
    QPixmap scaledPixmapApp = appPixmap.scaled(widthApp, heightApp, Qt::KeepAspectRatio);
    QPalette paletteApp;
    paletteApp.setBrush(QPalette::Background, scaledPixmapApp);
    logo->setAutoFillBackground(true);
    logo->setPalette(paletteApp);

    //声音选择界面中pyttsx3,微软和谷歌的图标
    QLabel *microsoft = ui->micosoftIcon;
    QLabel *google = ui->googleIcon;
    QLabel *python = ui->pythonIcon;
    QPixmap microPixmap(":/icons/images/microsoft.png");
    QPixmap googlePixmap(":/icons/images/google.png");
    QPixmap pythonPixmap(":/icons/images/python.png");
    int width2 = 50;
    int height2 = 50;
    int widthp = 60;
    int heightp = 60;
    QPixmap scaledPixmap1 = microPixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmap2 = googlePixmap.scaled(width2, height2, Qt::KeepAspectRatio);
    QPixmap scaledPixmap3 = pythonPixmap.scaled(widthp, heightp, Qt::KeepAspectRatio);
    QPalette palette1;
    QPalette palette2;
    QPalette palettep;
    palette1.setBrush(QPalette::Background, scaledPixmap1);
    palette2.setBrush(QPalette::Background, scaledPixmap2);
    palettep.setBrush(QPalette::Background, scaledPixmap3);
    microsoft->setAutoFillBackground(true);
    google->setAutoFillBackground(true);
    python->setAutoFillBackground(true);
    microsoft->setPalette(palette1);
    google->setPalette(palette2);
    python->setPalette(palettep);

    //声音选择界面中聊天框的图标
    QLabel *voiceDesc = ui->voiceDescription;
    QPixmap descPixmap(":/icons/images/chat.png");
    int width3 = 322;
    int height3 = 212;
    QPixmap scaledPixmapDesc = descPixmap.scaled(width3, height3, Qt::KeepAspectRatio);
    QPalette palette3;
    palette3.setBrush(QPalette::Background, scaledPixmapDesc);
    voiceDesc->setAutoFillBackground(true);
    voiceDesc->setPalette(palette3);

}

//style function: 实现渐变效果
void MainWindow::paintEvent(QPaintEvent *event)
{
    Q_UNUSED(event);
    // 在 paintEvent 中绘制渐变背景
    QPainter painter(this);
    // 创建渐变对象
    QLinearGradient gradient(0, 0, 0, height());
    switch(nowTheme)
        {
            case 0:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::darkGray);
                break;
            case 1:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::lightGray);
                break;
            case 2:
                gradient.setColorAt(0, Qt::darkGray);
                gradient.setColorAt(1, Qt::black);
                break;
            case 3:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::white);
                break;
            case 4:
                gradient.setColorAt(0, Qt::white);
                gradient.setColorAt(1, Qt::white);
                break;
            case 5:
                gradient.setColorAt(0, Qt::lightGray);
                gradient.setColorAt(1, Qt::darkGray);
                break;
            default:
                // 默认操作，如果选择了未处理的项
                break;
        }
    // 使用渐变填充背景
    painter.fillRect(rect(), QBrush(gradient));
}

//slot function: 切换全局样式
void MainWindow::onComboBoxIndexChanged(int index)
{
    nowTheme = index;
    QString style = GlobalStyle::getInstance().getStyle(index, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}

//slot function: 根据列表项的索引切换到相应的子页面
void MainWindow::on_menuList_currentRowChanged(int currentRow)
{
    ui->pages->setCurrentIndex(currentRow);
}

//tts-slot:
void MainWindow::checkSlot1(bool flag)
{
    if(flag==true)
    {
        ttsMode = 1;
    }
}
void MainWindow::checkSlot2(bool flag)
{
    if(flag==true)
    {
        ttsMode = 2;
    }
}
void MainWindow::checkSlot3(bool flag)
{
    if(flag==true)
    {
        QMessageBox::information(this,
            tr("谷歌语音"),
            tr("谷歌语音需要在vpn联网环境下使用。"),
            QMessageBox::Ok | QMessageBox::Cancel,
            QMessageBox::Ok);
        ttsMode = 3;
    }
}
//导入python模块
void MainWindow::importPythonModules()
{
    //DetectionScript.py模块
    pModule1 = PyImport_ImportModule("DetectionScript");
    if (!pModule1) {
        PyErr_Print(); // 输出详细错误信息
    }
    //RecognizitionScript.py模块
    pModule2 = PyImport_ImportModule("RecognizitionScript");
    if (!pModule2) {
        PyErr_Print();
    }
    //微软tts.py模块
    tts = PyImport_ImportModule("tts");
    if (!tts) {
        PyErr_Print();
    }
    //pyttsx3Script.py模块
    pyttsx3 = PyImport_ImportModule("pyttsx3Script");
    if (!pyttsx3) {
        PyErr_Print();
    }
    gtts  = PyImport_ImportModule("gttsScript");
    if (!gtts) {
        PyErr_Print();
    }
}

//导入python方法
void MainWindow::importPythonFunctions()
{
    pDeteImport = PyObject_GetAttrString(pModule1,"DetectionPipelines");
    if(!pDeteImport){
        PyErr_Print();
    }
    pRecoImport = PyObject_GetAttrString(pModule2,"RecognizitionPipelines");
    if(!pRecoImport){
        PyErr_Print();
    }
    pDeteOcr = PyObject_GetAttrString(pModule1,"runDetection");
    if(!pDeteOcr){
        PyErr_Print();
    }
    pRecoOcr = PyObject_GetAttrString(pModule2,"runRecognizition");
    if(!pRecoOcr){
        PyErr_Print();
    }
    changeText = PyObject_GetAttrString(tts,"changeText");
    if(!changeText){
        PyErr_Print();
    }
    changeRate = PyObject_GetAttrString(tts,"changeRate");
    if(!changeRate){
        PyErr_Print();
    }
    changePitch = PyObject_GetAttrString(tts,"changePitch");
    if(!changePitch){
        PyErr_Print();
    }
    changeVoice = PyObject_GetAttrString(tts,"changeVoice");
    if(!changeVoice){
        PyErr_Print();
    }
    speak_microsoft = PyObject_GetAttrString(tts,"speak");
    if(!speak_microsoft){
        PyErr_Print();
    }
    setPyttsx3 = PyObject_GetAttrString(pyttsx3,"getVoices");
    if(!setPyttsx3){
        PyErr_Print();
    }
    speak_pyttsx3 = PyObject_GetAttrString(pyttsx3,"speak");
    if(!speak_pyttsx3){
        PyErr_Print();
    }
    speak_gtts = PyObject_GetAttrString(gtts,"speak");
    if(!speak_gtts){
        PyErr_Print();
    }
    generateMp3 = PyObject_GetAttrString(tts,"generateAudio");
    if(!generateMp3){
        PyErr_Print();
    }

}

//为每个控件安装事件过滤器
void MainWindow::installFilter()
{
    QList<QLabel*> labelList = MainWindow::findChildren<QLabel*>();
    for (QLabel* label : labelList) {
        label->installEventFilter(this);
    }
    QList<QPushButton*> buttonList = MainWindow::findChildren<QPushButton*>();
    for (QPushButton* button : buttonList) {
        button->installEventFilter(this);
    }
}

//朗读文本-microsoft version
void MainWindow::microsoftSpeak()
{
    PyObject_CallObject(speak_microsoft, NULL);
}
//朗读文本-google version
void MainWindow::googleSpeak(QString text)
{
    QString language;
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    if(ui->comboBox_google->currentIndex() == 0)
        language = "zh-cn";
    else
        language = "en";
    PyObject* arg2 = PyUnicode_DecodeUTF8(language.toUtf8().constData(), strlen(language.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(2, arg1, arg2);

    PyObject_CallObject(speak_gtts, args);
    Py_DECREF(args);
}
//朗读文本-pyttsx3 version
void MainWindow::pyttsSpeak(QString text)
{
    QString voice = ui->comboBox_pyttsx3->currentText();
    PyObject* arg1 = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* arg2 = PyUnicode_DecodeUTF8(voice.toUtf8().constData(), strlen(voice.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(2, arg1, arg2);
    PyObject_CallObject(speak_pyttsx3, args);
}
//朗读文本
void MainWindow::speakText(QString text)
{
    switch (ttsMode) {
    case 1:
        pyttsSpeak(text);
        break;
    case 2:
        //textChange(text);
        //microsoftSpeak();
        break;
    case 3:
        googleSpeak(text);
        break;
    default:
        break;
    }
}
//改变SSML.xml中的文本
void MainWindow::textChange(QString text)
{
    PyObject* arg = PyUnicode_DecodeUTF8(text.toUtf8().constData(), strlen(text.toUtf8().constData()), "strict");
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changeText, args);
    //Py_XDECREF(arg);
    //Py_XDECREF(args);
}

//展示语速的值
void MainWindow::updateratevalue(int value)
{
    ui->rateSliderValue->setText(QString::number(value));
}
//展示音高的值
void MainWindow::updatepitchvalue(int value)
{
    ui->pitchSliderValue->setText(QString::number(value));
}
//调节放大镜放大的倍数
void MainWindow::updatezoomvalue(int value)
{
    qDebug() << value;
    if (value <= 25)
        zoom = 2.0;
    else if (value <= 50)
        zoom = 3.0;
    else if (value <= 75)
        zoom = 4.0;
    else
        zoom = 6.0;
}

//Hoykeys-slots: 放大镜
void MainWindow::magnifierWindowSlot()
{
    if (!isMagnifierEnabled)
    {
        // 开启放大镜
        magnifier = new MagnifierWindow(NULL, zoom);
        magnifier->show();
        isMagnifierEnabled = true;
    }
    else
    {
        // 关闭放大镜
        delete magnifier;
        magnifier = nullptr;
        isMagnifierEnabled = false;
    }
}
//Hotkeys-slots: 将窗口正常化
void MainWindow::normalizeWindow()
{
    this->showNormal();
}
//Hotkeys-slots: 开始使用
void MainWindow::hotkeyStart()
{
    on_btnStart_clicked();
}
//Hotkeys-slots: 退出使用
void MainWindow::hotkeyQuit()
{
    QApplication::quit();
}
//Hoykeys-slots: 文本框
void MainWindow::showTextWindowSlots()
{
    if (!isTextWindowEnabled)
    {
        // 开启文本框
        on_showTextArea_clicked();
        isTextWindowEnabled = true;
    }
    else
    {
        // 关闭文本框
        on_showTextCancel_clicked();
        isTextWindowEnabled = false;
    }
}

void MainWindow::menulistItemChanged(QListWidgetItem *current, QListWidgetItem *previous)
{
    if(current != nullptr && enableAudioTips)
    {
        //textChange(current->text());
        //todo speakText();
    }
}

bool MainWindow::eventFilter(QObject *obj, QEvent *event)
{
    //鼠标进入
    if ((obj->inherits("QPushButton") || obj->inherits("QLabel")) && event->type() == QEvent::MouseButtonPress)
    {
        if(QPushButton *btn = qobject_cast<QPushButton*>(obj))
        {
            QString btntext = btn->text();
            if(enableAudioTips)
            {
                speakText(btntext);
            }
        }
        else if(QLabel *label = qobject_cast<QLabel*>(obj))
        {
            QString labeltext = label->text();
            if(enableAudioTips)
            {
                speakText(labeltext);
            }
        }
    }
    //鼠标离开
    else if ((obj->inherits("QPushButton") || obj->inherits("QLabel")) && event->type() == QEvent::Leave)
    {
        if (QPushButton* button = qobject_cast<QPushButton*>(obj))
        {
            //qDebug() << "Mouse left QPushButton: ";
        }
        else if (QLabel* label = qobject_cast<QLabel*>(obj))
        {
            //qDebug() << "Mouse left QLabel: ";
        }
    }
    return QMainWindow::eventFilter(obj, event);
}
//退出使用
void MainWindow::on_btnCancel_clicked()
{
    QApplication::quit();
}

//将导入两个模型的操作放在预处理中进行,测试容忍值的临界值，提高软件开启的速度
void MainWindow::preHandle()
{
    //调用pDeteImport函数,用来导入文本检测,文本识别的模型
    /*PyObject_CallFunction(pDeteImport,NULL);
    PyObject_CallFunction(pRecoImport,NULL);
    preHandleTimer->stop();
    delete preHandleTimer;*/
}
//开始使用
void MainWindow::on_btnStart_clicked()
{
    showMinimized();

    cutimage->captureNowFullScreen();
    cutimage->captureLastFullScreen();

    //ocr-detection
    PyObject* pResultD = PyObject_CallObject(pDeteOcr,NULL);
    if(pResultD) {
        //将返回值转化为string类型
        PyObject* reprD = PyObject_Repr(pResultD);
        PyObject* strD = PyUnicode_AsEncodedString(reprD, "utf-8", "strict");
        QString resultD = PyBytes_AsString(strD);
        GlobalArray::getInstance().setArray(resultD);
        Py_XDECREF(pResultD);  // 释放Python对象
    } else {
        PyErr_Print();
    }

    ocrTimer->start(3800);
    posTimer->start(400);
    PyGC_Collect();
}

//python-microsoft-tts

/*设置语速-1.0到1.0*/
void MainWindow::setRate(int rate)
{
    qDebug() << rate;
    PyObject* arg = PyLong_FromLong(rate);
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changeRate, args);
}
/*设置音高-1.0到1.0*/
void MainWindow::setPitch(int pitch)
{
    qDebug() << pitch;
    PyObject* arg = PyLong_FromLong(pitch);
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changePitch, args);
}
/*选择声音*/
void MainWindow::onvoicechange(int value)
{
    qDebug() << value;
    PyObject* arg = PyLong_FromLong(value);
    PyObject* args = PyTuple_Pack(1, arg);
    PyTuple_SetItem(args, 0, arg);
    PyObject_CallObject(changeVoice, args);
    QComboBox *voicechange = ui->comboBox_microsoft;
    QString text1 = voicechange->currentText();
    QString text2 = "您好，我是";
    speakText(text2 + text1);
}

void MainWindow::mouseInText()
{
    nowPos = QCursor::pos();
    temptVector = GlobalArray::getInstance().isTextIn(nowPos.x(), nowPos.y());
    if(!(temptVector.isEmpty()) && temptVector != textVector)
    {
        textVector = temptVector;
        cutimage->captureTextPosition(textVector);
        PyObject* pResultR = PyObject_CallObject(pRecoOcr,NULL);
        if(pResultR) {
            //将返回值转化为string类型
            PyObject* reprR = PyObject_Repr(pResultR);
            PyObject* strR = PyUnicode_AsEncodedString(reprR, "utf-8", "strict");
            QString resultR = PyBytes_AsString(strR);
            int length = resultR.length();
            QString text = resultR.mid(12, length-15).remove("\\").remove("'");
            speakText(text);
            Py_XDECREF(pResultR);  // 释放Python对象
        } else {
            PyErr_Print();
        }
    }
}

void MainWindow::handleImgChange()
{
   if (cutimage->compareImages(tolerance))
   {
       qDebug() << "界面内容没有发生变化";
       cutimage->captureLastFullScreen();
   }
   else
   {
       qDebug() << "界面内容发生了变化";
       cutimage->captureNowFullScreen();
       cutimage->captureLastFullScreen();

       //ocr-detection
       PyObject* pResultD = PyObject_CallObject(pDeteOcr,NULL);
       if(pResultD) {
           //将返回值转化为string类型
           PyObject* reprD = PyObject_Repr(pResultD);
           PyObject* strD = PyUnicode_AsEncodedString(reprD, "utf-8", "strict");
           QString resultD = PyBytes_AsString(strD);
           GlobalArray::getInstance().setArray(resultD);
           Py_XDECREF(pResultD);  // 释放Python对象
       } else {
           PyErr_Print();
       }
   }
}

//调用python脚本来实现微软tts功能
/*TextToSpeechTask::TextToSpeechTask(const QString& text)
    : m_text(text)
{
}
void TextToSpeechTask::run()
{
    try {
        // 这里放入调用 Python 脚本的代码来优化交互体验
        //qDebug() << "TextToSpeechTask: " << m_text;
        TextToSpeech *texttospeech = new TextToSpeech();
        texttospeech->speak(m_text);
    } catch (const QString& errorMsg) {
        qDebug() << errorMsg;
    }
}*/

//设置小号字体
void MainWindow::on_setSmallFont_clicked()
{
    fontSize = 0;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}
//设置中号字体
void MainWindow::on_setMiddleFont_clicked()
{
    fontSize = 1;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}
//设置大号字体
void MainWindow::on_setBigFont_clicked()
{
    fontSize = 2;
    int currentIndex = ui->comboBoxStyle->currentIndex();
    QString style = GlobalStyle::getInstance().getStyle(currentIndex, fontSize);
    MainWindow::setStyleSheet(style);
    playAudio();
    showTextBox();
}

//保存音频文件
void MainWindow::on_generateButton_clicked()
{
    QString text = ui->audioText->toPlainText();
    audioPath = ui->audioPath->text();

    QMessageBox::information(this,
        tr("保存音频"),
        tr("音频保存成功!"),
        QMessageBox::Ok | QMessageBox::Cancel,
        QMessageBox::Ok);

    ui->audioText->setText("");
}
void MainWindow::on_generateButton_listen_clicked()
{
    mediaPlayer->setMedia(QUrl::fromLocalFile(audioPath));
    mediaPlayer->play();
}
/*tools functions*/
//开启语音提示功能
void MainWindow::on_setPlayVisible_clicked()
{
    enableAudioTips = true;
    ui->play_language->setVisible(true);
    ui->play_voice->setVisible(true);
    ui->play_changeTheme->setVisible(true);
    ui->play_start->setVisible(true);
    ui->play_quit->setVisible(true);
    ui->play_menuItem1->setVisible(true);
    ui->play_menuItem2->setVisible(true);
    ui->play_menuItem3->setVisible(true);
    ui->play_menuItem4->setVisible(true);
    ui->play_menuItem5->setVisible(true);
    ui->play_menuItem6->setVisible(true);
    ui->play_shortcut1->setVisible(true);
    ui->play_shortcut2->setVisible(true);
    ui->play_voicedescription->setVisible(true);
    ui->play_microsoft->setVisible(true);
    ui->play_google->setVisible(true);
    ui->Audio1->setVisible(true);
    ui->Audio2->setVisible(true);
    ui->Audio3->setVisible(true);
    ui->Audio4->setVisible(true);
    ui->Audio5->setVisible(true);
    ui->Audio6->setVisible(true);
    ui->Audio7->setVisible(true);
    ui->Audio8->setVisible(true);
    ui->Audio9->setVisible(true);
    ui->Audio11->setVisible(true);
    ui->Audio12->setVisible(true);
    ui->Audio13->setVisible(true);
}
//关闭语音提示功能
void MainWindow::on_setPlayInvisible_clicked()
{
    enableAudioTips = false;
    ui->play_language->setVisible(false);
    ui->play_voice->setVisible(false);
    ui->play_changeTheme->setVisible(false);
    ui->play_start->setVisible(false);
    ui->play_quit->setVisible(false);
    ui->play_menuItem1->setVisible(false);
    ui->play_menuItem2->setVisible(false);
    ui->play_menuItem3->setVisible(false);
    ui->play_menuItem4->setVisible(false);
    ui->play_menuItem5->setVisible(false);
    ui->play_menuItem6->setVisible(false);
    ui->play_shortcut1->setVisible(false);
    ui->play_shortcut2->setVisible(false);
    ui->play_voicedescription->setVisible(false);
    ui->play_microsoft->setVisible(false);
    ui->play_google->setVisible(false);
    ui->Audio1->setVisible(false);
    ui->Audio2->setVisible(false);
    ui->Audio3->setVisible(false);
    ui->Audio4->setVisible(false);
    ui->Audio5->setVisible(false);
    ui->Audio6->setVisible(false);
    ui->Audio7->setVisible(false);
    ui->Audio8->setVisible(false);
    ui->Audio9->setVisible(false);
    ui->Audio11->setVisible(false);
    ui->Audio12->setVisible(false);
    ui->Audio13->setVisible(false);
}
//切换鼠标样式
void MainWindow::on_changeCursor_clicked()
{
    // 初始化随机数生成器
    QTime time = QTime::currentTime();
    qsrand(static_cast<uint>(time.msec()));
    int randomNumber = qrand() % 6; // 范围为0到5
    switch (randomNumber) {
        case 0:
            QApplication::setOverrideCursor(QCursor(Qt::WhatsThisCursor));
          break;
        case 1:
            QApplication::setOverrideCursor(QCursor(Qt::WaitCursor));
          break;
        case 2:
            QApplication::setOverrideCursor(QCursor(Qt::SizeAllCursor));
          break;
        case 3:
            QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor));
          break;
        case 4:
            QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor));
          break;
        case 5:
            QApplication::setOverrideCursor(QCursor(Qt::OpenHandCursor));
          break;
        default:
          break;
    }
}
//默认鼠标样式
void MainWindow::on_recoverCursor_clicked()
{
    // 恢复默认鼠标光标
    QApplication::restoreOverrideCursor();
}
//绘制文本框
void MainWindow::on_showTextArea_clicked()
{
    cutimage->captureNowFullScreen();
    //处理全屏截图获得文字框的坐标值
    PyObject* pResultD = PyObject_CallObject(pDeteOcr,NULL);
    if(pResultD) {
        //将返回值转化为string类型
        PyObject* reprD = PyObject_Repr(pResultD);
        PyObject* strD = PyUnicode_AsEncodedString(reprD, "utf-8", "strict");
        QString resultD = PyBytes_AsString(strD);
        GlobalArray::getInstance().setArray(resultD);
        Py_XDECREF(pResultD);  // 释放Python对象
    } else {
        PyErr_Print();
    }
    QVector<QVector<int>> array = GlobalArray::getInstance().getArray();
    // 绘制文本框
    textwindow = new ShowTextWindow();
    textwindow->setRectangles(array);
    textwindow->show();
    isTextWindowEnabled = true;
}
//取消显示文本框
void MainWindow::on_showTextCancel_clicked()
{
    // 关闭放大镜
    delete textwindow;
    textwindow = nullptr;
    isTextWindowEnabled = false;
}

MainWindow::~MainWindow()
{
    delete magnifier;
    delete magnifierKey;
    delete normalizeKey;
    delete cutimage;
    delete posTimer;
    delete ocrTimer;
    //ocr
    Py_XDECREF(pModule1);
    Py_XDECREF(pModule2);
    Py_XDECREF(pDeteImport);
    Py_XDECREF(pRecoImport);
    Py_XDECREF(pDeteOcr);
    Py_XDECREF(pRecoOcr);
    //tts
    Py_XDECREF(tts);
    Py_XDECREF(pyttsx3);
    Py_XDECREF(gtts);
    Py_XDECREF(speak_microsoft);
    Py_XDECREF(speak_gtts);
    Py_XDECREF(speak_pyttsx3);
    Py_XDECREF(changeText);
    Py_XDECREF(setPyttsx3);
    Py_Finalize();
    delete ui;
}

